package com.junqi.sys.application.controller.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.junqi.sys.common.utils.MimeTypeUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/common")
public class CommonController {

    /**
     * 文件地址
     */
    @Value(value = "${jq.file_path}")
    private String filePath="";
    @Value(value = "${jq.file_prefix_url}")
    private String filePrefixUrl="";

    // 图片上传接口
    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }
        try {
            // 保存文件路径  upload/20250101/文件名_随机数.文件格式
            String fileName =FilenameUtils.getBaseName(file.getOriginalFilename())+"_"+RandomUtil.randomNumbers(6)+"_"+getExtension(file);
            String date=DateUtil.formatDate(new Date());
            String absPath = getAbsoluteFile(filePath, date + File.separator +fileName).getAbsolutePath();
            file.transferTo(Paths.get(absPath));
            // 返回文件访问 URL
            String fileUrl = filePrefixUrl+date+"/"+fileName;
            return ResponseEntity.ok(fileUrl);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
        }
    }

    public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StrUtil.isBlank(extension))
        {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    //文件预览接口
    @GetMapping("/file/{date}/{fileName}")
    public void getfile(@PathVariable("date") String date, @PathVariable("fileName") String fileName,HttpServletResponse response) {
        File file = new File(filePath, date + File.separator +fileName);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        try (InputStream inputStream = new FileInputStream(file)) {
            // 动态设置 MIME 类型
            String mimeType = Files.probeContentType(file.toPath());
            if (mimeType == null) {
                mimeType = "application/octet-stream";
            }
            response.setContentType(mimeType);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + file.getName() + "\"");
            // 输出文件内容
            byte[] buffer = new byte[1024];
            int bytesRead;
            OutputStream outputStream = response.getOutputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}
